package com.zuoshuai.dispatcher;

import java.lang.reflect.Method;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {
	private static Log log = LogFactory.getLog(DataSourceAdvice.class);
	private long beginTime = 0;

	@Override
	public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
		// TODO Auto-generated method stub
		log.info("结束业务处理[" + method.getName() + "];耗时:" + (System.currentTimeMillis() - beginTime) + "毫秒;全路径["
				+ target.getClass().getName() + "]");
		log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
	}

	public void before(Method method, Object[] args, Object target) throws Throwable {
		// TODO Auto-generated method stub
		log.info("开始业务处理[" + method.getName() + "];全路径[" + target.getClass().getName() + "]");
		beginTime = System.currentTimeMillis();
		log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		if (method.getName().startsWith("add") || method.getName().startsWith("create") || method.getName().startsWith("del")
				|| method.getName().startsWith("edit") || method.getName().startsWith("insert")
				|| method.getName().startsWith("save") || method.getName().startsWith("update")
				|| method.getName().startsWith("modeify")) {
			log.info("数据源切换到:master");
			DatasourceHandler.setDataSourceType("master");
			log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		} else {
			log.info("数据源切换到:slave");
			DatasourceHandler.setDataSourceType("slave");
			log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
		}
	}
	public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
		log.info("数据源调用发生异常,数据源切换到:slave");
		DatasourceHandler.setDataSourceType("slave");
		log.error("数据源调用异常信息:" + ex.getMessage());
		log.info("数据源调用异常信息:" + ex.getMessage());
		log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
	}

}
